package common.utilities;

import java.io.*;
import java.net.*;

public class MulticastNode {

	InetAddress group = null;
	MulticastSocket s = null;

//	String mcastAddr="228.0.0.4";
//   int mcastPort=45564;
   String mcastAddr="224.0.0.1";
   int mcastPort=12345;


   public static void main (String[] args) {
      if (args.length > 0) {
         System.out.println("Sending message: " + args[0]);

         // Startup this MulticastNode
         MulticastNode node = new MulticastNode();

         // Send the message
         node.send(args[0]);

         // Listen in on the multicast group, and print all messages
         node.receive();
      } else {
         System.out.println("Need an argument string to send.");
         System.exit(1);
      }
   }

   public MulticastNode() {
      try {
         group = InetAddress.getByName(mcastAddr);
         s = new MulticastSocket(mcastPort);
         s.joinGroup(group);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public void send(String msg) {
      try {
         DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), group, mcastPort);
         s.send(hi);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }

   public void receive() {
      byte[] buf;

      // Loop forever
      while (true) {
         try {
            buf = new byte[1000];
            DatagramPacket recv = new DatagramPacket(buf, buf.length);
            s.receive(recv);
            System.out.println("Received: " + new String(buf));
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
   }

}

// End of MulticastNode.java
